package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.User;
import dao.UserDao;

/**
 * 处理登录的Servlet，login.html页面登录表单的数据将提交到本Servlet。
 * 
 * @author Steven Suo
 *
 */
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * 登录验证码在RandomNumberServlet中生成，并保存在session对象中。
     * @see RandomNumberServlet#doGet(HttpServletRequest, HttpServletResponse)
     */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		//获取正确的验证码
		String code = (String)request.getSession().getAttribute("checkCode");
		//获取用户提交的验证码
		String checkCode = request.getParameter("checkCode");
		//检查验证码是否正确，忽略大小写。如果正确，则验证用户的用户名和密码是否正确。
		if (code.equalsIgnoreCase(checkCode)) {
			String userName = request.getParameter("userName");
			String pwd = request.getParameter("pwd");
			UserDao dao = new UserDao();
			User user = dao.findByNameAndPwd(userName, pwd);
			//用户名密码正确，则将User对象保存到session中。
			if (user!=null) {
				request.getSession().setAttribute("loginUser", user);
				response.sendRedirect("home.jsp");
			}else{
				out.println("用户名或密码错误，请重新登录。");
				response.setHeader("Refresh", "2;URL=login.html");
			}
		}else{
			out.println("验证码错误，请重新登录。");
			response.setHeader("Refresh", "2;URL=login.html");
		}
		out.close();
	}

}
